package frsf.cidisi.exercise.arqueologo.search.actions;

import java.util.ArrayList;

import Clases.Aldea;
import frsf.cidisi.exercise.arqueologo.search.*;
import frsf.cidisi.faia.agent.search.SearchAction;
import frsf.cidisi.faia.agent.search.SearchBasedAgentState;
import frsf.cidisi.faia.state.AgentState;
import frsf.cidisi.faia.state.EnvironmentState;
import java.util.logging.Level;
import java.util.logging.Logger;

public class IrIcaedur extends SearchAction {

    /**
     * This method updates a tree node state when the search process is running.
     * It does not updates the real world state.
     */
    @Override
	public SearchBasedAgentState execute(SearchBasedAgentState s) {
		ArqueologoAgentState agState = (ArqueologoAgentState) s;
		if (agState.getAldeasVisitadas().contains(Aldea.ICAEDUR)) {
			return null;
		}

		// BUSCAMOS EL VECINO
		ArrayList<String> vecinos = new ArrayList<String>();
		vecinos.addAll(agState.getVecinos());
		if (vecinos != null) {
			int indice = vecinos.indexOf(Aldea.ICAEDUR);
			if (indice >= 0) {
				
				int distanciaAreccorrer = agState.getmundo().getDistancias()[agState
						.getmundo().getNombres().indexOf(agState.getPosicion())][agState
						.getmundo().getNombres().indexOf(Aldea.ICAEDUR)];
				
				agState.sumarDistancia(distanciaAreccorrer);
				agState.getAldeasVisitadas().add(Aldea.ICAEDUR);
				agState.setPosicion(Aldea.ICAEDUR);
				
				return agState;
			}
		}

		return null;
	}

	/**
	 * This method updates the agent state and the real world state.
	 */
	@Override
	public EnvironmentState execute(AgentState ast, EnvironmentState est) {
		ArqueologoEnvironmentState environmentState = (ArqueologoEnvironmentState) est;
		ArqueologoAgentState agState = ((ArqueologoAgentState) ast);
		if (agState.getAldeasVisitadas().contains(Aldea.ICAEDUR)) {
			return null;
		}
		ArrayList<String> vecinos = new ArrayList<String>();
		vecinos.addAll(agState.getVecinos());
		if (vecinos != null) {
			int indice = vecinos.indexOf(Aldea.ICAEDUR);
			if (indice >= 0) {
				
				int distanciaAreccorrer = (agState.getmundo().getDistancias()[agState
						.getmundo().getNombres().indexOf(agState.getPosicion())][agState
						.getmundo().getNombres().indexOf(Aldea.ICAEDUR)]);
				
				agState.sumarDistancia(distanciaAreccorrer);
				agState.setPosicion(Aldea.ICAEDUR);
				environmentState.setposicionArqueologo(Aldea.ICAEDUR);
				agState.getAldeasVisitadas().add(Aldea.ICAEDUR);
                                agState.marcarVisitas(agState.getAldeasVisitadas());
				return environmentState;
			}
		}

		return null;
	}

    /**
     * This method returns the action cost.
     */
    @Override
    public Double getCost() {
        return new Double(0);
    }

    /**
     * This method is not important for a search based agent, but is essensial
     * when creating a calculus based one.
     */
    @Override
    public String toString() {
        return "IrIcaedur";
    }
}